/**
 * 
 */
package com.estock.common;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.estock.common.util.support.ESLogger;

/**
 * @author richard
 *
 */
public class ESConfig {
	
	protected static final ESLogger logger = ESLogger.getLogger(ESConfig.class);
	
	private static Object instanceLock = new Object();
	
	public static final String VISIT_LOG_INDEX_ENABLE = "visit.log.index.enable";
	
	public static final String WIN_DATA_DIR_KEY = "win.data.dir";
	public static final String UNIX_DATA_DIR_KEY = "unix.data.dir";
	
	private static String winDataFileDir;
	private static String unixDataFileDir;
    
    private static ESConfig instance;
    private ESConfig() {}
    
    public static ESConfig getInstance() {
    	synchronized (instanceLock) {
    		if (instance == null) {
        		instance = new ESConfig();
        		load();
        	}
        	return instance;
		}
    }
    
    public String getDataFileDir() {
    	String os = System.getProperty("os.name");
    	if (os.toLowerCase().contains("win")) {
    		return winDataFileDir;
    	} else {
    		return unixDataFileDir;
    	}
	}
    
	private static void load() {
    	InputStream inputStream = null;
        try {
            Properties props = new Properties();
            inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties");

            if (inputStream == null) {
                throw new FileNotFoundException("[config.properties] is not found!");
            }
            props.load(inputStream);
            
            winDataFileDir = props.getProperty(WIN_DATA_DIR_KEY);
            unixDataFileDir = props.getProperty(UNIX_DATA_DIR_KEY);
        }
        catch (FileNotFoundException e) {
            logger.info("Initial Config error");
            throw new RuntimeException(e);
        } catch (IOException ioe) {
            logger.info("load stream error");
            throw new RuntimeException(ioe);
        } catch (NumberFormatException nEx) {
            logger.info("Parse properties integer error");
            throw new RuntimeException(nEx);
        }
        finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                }
                catch (IOException e) {
                    logger.info("Input stream close failed" + e);
                }
            }
        }
    }

}
